﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace SimpleClient
{
    public class LoginViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private string _userName = string.Empty;
        public string UserName
        {
            get
            {
                return _userName;
            }
            set
            {
                _userName = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("UserName"));
            }
        }
        //private string _passWord = string.Empty;
        //public string PassWord 
        //{
        //    get
        //    {
        //        return _passWord;
        //    }
        //    set
        //    {
        //        _passWord = value;
        //        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("PassWord"));
        //    }
        //}
        public DelegateCommand LoginCommand { get; set; }
        public Action CloseAction;
        public LoginViewModel()
        {
            LoginCommand = new DelegateCommand((o) => Login(o), (o) => { return true; });

        }

        private void Login(object obj)
        {
            try
            {
                if (obj == null)
                {
                    Console.WriteLine("获取密码失败！obj is null.");
                    return;
                }
                PasswordBox passwordBox = obj as PasswordBox;
                if (passwordBox == null)
                {
                    Console.WriteLine("获取密码失败！passwordBox is null.");
                    return;
                }
                LoginModel model = new LoginModel();
                if(model.Login(UserName, passwordBox.Password))
                {
                    MainWindow mainWindow = new MainWindow();
                    mainWindow.Show();
                    App.Current.Dispatcher.Invoke((Action)(() =>
                    {
                        this.CloseAction.Invoke();
                    }));
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("登录失败，"+ex);
            }
        }
    }
}
